package com.coin900.coin.server.coin.ctrl;

import com.coin900.coin.base.AjaxResponse;
import com.coin900.coin.base.CoinConstants;
import com.coin900.coin.base.FuConstants;
import com.coin900.coin.base.utils.RequestUtil;
import com.coin900.coin.persist.coin.CoinProjectCoinVO;
import com.coin900.coin.persist.coin.CoinProjectVO;
import com.coin900.coin.persist.coin.CoinUserProjectVO;
import com.coin900.coin.persist.fu.FuUserVO;
import com.coin900.coin.persist.fu.FuUserWalletVO;
import com.coin900.coin.service.coin.ICoinProjectService;
import com.coin900.coin.service.fu.IFuUserService;
import com.coin900.coin.service.fu.IFuUserWalletService;
import com.value.exception.BusinessException;
import com.value.mybatis.Pagination;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 项目
 *
 * @author shui
 * @create 2017-11-21
 **/
@Controller
public class CoinProjectCtrl extends CoinController {


    /**
     * 项目首页
     * - 按照项目购买的人数和创建时间排序
     *
     * @param viewType
     * @param request
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(@RequestParam(required = false) String viewType,
                              HttpServletRequest request) {

        if (CoinConstants.COIN_PAGE.equals(viewType)) {
            ModelAndView modelAndView = super.buildView(request, "index");
            return modelAndView;
        }

        AjaxResponse ajaxResponse = super.buildAjaxResponse(request);
        Pagination pagination = RequestUtil.buildPage(request);
        Map<String, Object> params = pagination.getParams();
        params.put("publishStatus", CoinConstants.COIN_PUBLISH_STATUS_PUBLICHED);
        params.put("dataStatus", 1);
        List<CoinProjectVO> coinProjectVOS = this.coinProjectService.loadCoinProjectForPage(pagination);
        this.limitIntroduce(coinProjectVOS, 50);
        this.setProjectListData(coinProjectVOS);
        ajaxResponse.addModels(coinProjectVOS);
        return ajaxResponse.getMav();
    }


    /**
     * 项目详情页
     *
     * @param id
     * @param sourceUserId
     * @param request
     * @return
     */
    @RequestMapping(value = "/detail/{id}", method = RequestMethod.GET)
    public Object detail(@PathVariable String id,
                         @RequestParam(required = false) Long sourceUserId,
                         HttpServletRequest request) {
        FuUserVO user = getUser();
//        if (user != null && sourceUserId == null) {
//            return new RedirectView("/detail/" + id + "?viewType=page&&sourceUserId=" + user.getId(), false);
//        }
        // 已经发布的项目予以显示
        Map<String, Object> params = new HashMap<>();
        params.put("id", id);
        params.put("publishStatus", CoinConstants.COIN_PUBLISH_STATUS_PUBLICHED);
        params.put("dataStatus", 1);
        List<CoinProjectVO> coinProjectVOS = this.coinProjectService.loadCoinProject(params);
        if (coinProjectVOS.isEmpty()) {
            throw new BusinessException("项目不存在或未发布");
        }

        CoinProjectVO coinProjectVO = coinProjectVOS.get(0);
        // 设置项目状态名称
        String statusName = CoinConstants.COIN_PROJECT_STATUS.get(coinProjectVO.getStatus());
        coinProjectVO.setStatusName(statusName);
        // 计算剩余天数
        Date closeTime = coinProjectVO.getCloseTime();
        Date now = new Date();
        long remain = closeTime.getTime() - now.getTime() > 0 ? (closeTime.getTime() - now.getTime()) : 0;
        long days = remain / (1000 * 60 * 60 * 24);
        long hours = (remain % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60);
        coinProjectVO.setRemainDay(days + "天" + hours + "时");
        // 计算项目进度
        this.setAmountProgress(coinProjectVO);

        if (CoinConstants.COIN_PROJECT_STATUS_WAITING == coinProjectVO.getStatus()) {
            // 处于预售期，比例需要打折
            Double discount = coinProjectVO.getDiscount();
            List<CoinProjectCoinVO> projectCoinList = coinProjectVO.getProjectCoinList();
            if (!projectCoinList.isEmpty()) {
                for (CoinProjectCoinVO coinProjectCoinVO : projectCoinList) {
                    Double proportion = coinProjectCoinVO.getProportion();
                    proportion = proportion * discount;
                    coinProjectCoinVO.setProportion(proportion);
                }
            }
        }

        ModelAndView modelAndView = super.buildView(request, "project/detail");
        modelAndView.addObject("model", coinProjectVO);

        // 返回实名认证信息
        Integer idcardStatus = 0;
        if (user != null) {
            FuUserVO dbUser = this.userService.getUser(user.getId());
            if (dbUser != null) {
                idcardStatus = dbUser.getIdcardStatus();
            }
        }
        modelAndView.addObject("idcardStatus", idcardStatus);

        return modelAndView;
    }

    /**
     * 获取用户某种币的余额
     *
     * @param coinId
     * @return
     */
    @RequestMapping(value = "/wallet-balance", method = RequestMethod.GET)
    public Object detailUserWallet(@RequestParam Long coinId) {
        ModelAndView modelAndView = new ModelAndView();
        FuUserVO user = getUser();
        Map<String, Object> params = new HashMap<>();
        params.clear();
        params.put("userId", user.getId());
        params.put("coinId", coinId);
        params.put("dataStatus", 1);
        List<FuUserWalletVO> fuUserWalletVOS = this.walletService.loadFuUserWallet(params);
        if (!fuUserWalletVOS.isEmpty()) {
            FuUserWalletVO fuUserWalletVO = fuUserWalletVOS.get(0);
            modelAndView.addObject("balance", fuUserWalletVO.getAvailable());
            return modelAndView;
        } else {
            return null;
        }
    }

    /**
     * 项目中心
     * - 按照项目购买的人数和创建时间排序
     *
     * @param viewType
     * @param status   项目进度，1进行中 2即将 3已结束 null全部
     * @param request
     * @return
     */
    @RequestMapping(value = "/project-center", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false) String viewType,
                             @RequestParam(required = false) String status,
                             HttpServletRequest request) {

        if (FuConstants.FU_PAGE.equals(viewType)) {
            ModelAndView modelAndView = super.buildView(request, "project/center");
            return modelAndView;
        }

        AjaxResponse ajaxResponse = super.buildAjaxResponse(request);
        Pagination pagination = RequestUtil.buildPage(request);
        Map<String, Object> params = pagination.getParams();
        if (!StringUtils.isBlank(status)) {
            // 没有参数默认查询进行中项目
            params.put("status", status);
        }
        params.put("publishStatus", CoinConstants.COIN_PUBLISH_STATUS_PUBLICHED);
        params.put("dataStatus", 1);
        List<CoinProjectVO> coinProjectVOS = this.coinProjectService.loadCoinProjectForPage(pagination);
        this.limitIntroduce(coinProjectVOS, 50);
        this.setProjectListData(coinProjectVOS);
        ajaxResponse.addModels(coinProjectVOS);
        return ajaxResponse.getMav();
    }

    /**
     * 用户项目列表
     *
     * @param viewType
     * @param request
     * @return
     */
    @RequestMapping(value = "/project-list", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false) String viewType,
                             HttpServletRequest request) {

        if (CoinConstants.COIN_PAGE.equals(viewType)) {
            ModelAndView modelAndView = super.buildView(request, "project/project");
            return modelAndView;
        }

        FuUserVO user = super.getUser();
        Long userId = user.getId();
        AjaxResponse response = super.buildAjaxResponse(request);
        Pagination pagination = RequestUtil.buildPage(request);
        Map<String, Object> params = pagination.getParams();
        // 购买了的项目信息
        params.clear();
        params.put("userId", userId);
        params.put("dataStatus", 1);
        params.put("orderStatus", CoinConstants.COIN_ORDER_STATUS_PAID);
        List<CoinUserProjectVO> coinUserProjectList = this.coinProjectService.loadUserProjectForPage(pagination);

        if (!coinUserProjectList.isEmpty()) {
            for (CoinUserProjectVO coinUserProjectVO : coinUserProjectList) {
                Date closeTime = coinUserProjectVO.getCloseTime();
                SimpleDateFormat format = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
                String formatDate = format.format(closeTime);
                coinUserProjectVO.setCloseTimeFormat(formatDate);

                Integer status = coinUserProjectVO.getStatus();
                String statusName = CoinConstants.COIN_PROJECT_STATUS.get(status);
                coinUserProjectVO.setStatusName(statusName);
            }
            pagination.setResults(coinUserProjectList);
            response.addPagination(pagination);
        }

        return response.getMav();
    }

    /**
     * 项目列表添加额外的信息
     *
     * @param coinProjectVOS
     */
    private void setProjectListData(List<CoinProjectVO> coinProjectVOS) {
        for (CoinProjectVO coinProjectVO : coinProjectVOS) {
            String statusName = CoinConstants.COIN_PROJECT_STATUS.get(coinProjectVO.getStatus());
            coinProjectVO.setStatusName(statusName);
            // 计算剩余天数
            Date closeTime = coinProjectVO.getCloseTime();
            Date now = new Date();
            long remain = closeTime.getTime() - now.getTime() > 0 ? (closeTime.getTime() - now.getTime()) : 0;
            long days = remain / (1000 * 60 * 60 * 24);
            coinProjectVO.setRemainDay(String.valueOf(days));
            // 计算项目进度
            this.setAmountProgress(coinProjectVO);
            coinProjectVO.setModifiedDate(new Date());
        }
    }

    /**
     * 设置项目金额进度
     *
     * @param coinProjectVO
     */
    private void setAmountProgress(CoinProjectVO coinProjectVO) {
        Long fundedAmount = coinProjectVO.getFundedAmount();
        Long targetAmount = coinProjectVO.getTargetAmount();
        double statusNumber = (double) fundedAmount / targetAmount > 1 ? 1 : (double) fundedAmount / targetAmount;
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(2);
        coinProjectVO.setAmountProgress(nt.format(statusNumber));
    }

    /**
     * 项目简介截取 n 个字符
     *
     * @param projectList
     * @param n
     */
    private void limitIntroduce(List<CoinProjectVO> projectList, int n) {
        for (CoinProjectVO coinProjectVO : projectList) {
            this.limitIntroduce(coinProjectVO, n);
        }
    }

    /**
     * 项目简介截取 n 个字符
     *
     * @param projectVO
     * @param n
     */
    private void limitIntroduce(CoinProjectVO projectVO, int n) {
        String introduce = projectVO.getIntroduce();
        if (introduce != null && introduce.length() > 50) {
            introduce = introduce.substring(0, n);
            projectVO.setIntroduce(introduce);
        }
    }

    @Autowired
    private IFuUserService userService;
    @Autowired
    private IFuUserWalletService walletService;
    @Autowired
    private ICoinProjectService coinProjectService;

}
